package com.penghk.earth.Controller;

import com.penghk.earth.entity.App;
import com.penghk.earth.util.EhcacheUtil;
import com.penghk.contorller.persistence.GenericDaoSupport;
import com.penghk.contorller.persistence.GenericJdbcSupport;
import com.penghk.contorller.web.resolver.Page;
import com.penghk.contorller.web.resolver.Secure;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.HashMap;

@RestController
//@Controller
public class DemoController {

    @Autowired
    private GenericJdbcSupport genericJdbcSupport;

    @Autowired
    private GenericDaoSupport genericDaoSupport;


    @RequestMapping("/download")
    public ResponseEntity<byte[]> download() throws IOException {
        File file = new File("/home/penghk/50727_20171205.txt");
        byte[] body = null;
        InputStream in = new FileInputStream(file);
        body = new byte[in.available()];
        in.read(body);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Dispositon", "attchement;filename="+file.getName());
        HttpStatus status = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body,httpHeaders,status);
        return entity;
    }



    @RequestMapping("/secure")
    public void getSecure(@Secure Page page,String everyPage) {
        System.out.println(everyPage);
        System.out.println(page);
    }

    @RequestMapping("/demo")
    public String getString(){
        int count = genericJdbcSupport.queryForInt("select count(*) from app");
        genericDaoSupport.queryForInt("select count(*) from app");
        System.out.println("count : "+count);
        App app = null;
        app = genericDaoSupport.get(App.class,1);
        int count1 = genericDaoSupport.searchForInt("select count(*) from App a where 1 = 1");
        HashMap params = new HashMap();
        params.put("param1",1);
        int count2 = genericDaoSupport.searchForInt("select count(*) from App a where 1 = :param1",params);
        return app.toString();
    }

    @RequestMapping("/getAppByCache")
    public App getAppByCache(int id){
        Cache cache = EhcacheUtil.getInstance().get("ehcacheGO");
        Element element = cache.get("app"+id);
        App app;
        if(element==null||element.getObjectValue() == null){
            app = genericDaoSupport.get(App.class,id);
            EhcacheUtil.getInstance().put("ehcacheGO","app"+id,app);
        }else {
            app = (App) element.getObjectValue();
        }
        return app;
    }
}
